# coding:utf-8
import base64
from crypt import methods
import datetime
import json
import os
import random
import re
import time
from datetime import date
import uuid
from io import BytesIO

import requests
from flask_mail import Mail
from PIL import Image
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, jsonify, app, make_response, \
    current_app
from flask_mail import Message
from sqlalchemy import or_
from werkzeug.utils import secure_filename

import urllib
from App.ext import db, socketio
from App.validate_code import get_verify_code
from .models import User, Item, ShopCar, Order, Search, Provincial, Reduce, ChatMsg, History
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import qrcode
import cv2
from pyzbar.pyzbar import decode
from datetime import timedelta

# 查询商品信息
from App.ShowapiRequest import ShowapiRequest
import json

login = Blueprint('login', __name__)

UPLOAD_FOLDER = 'upload'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp3'])

if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
else:
    pass

@login.route('/createAll')
def create():
    db.create_all()
    return 'ok'

@login.route('/check', methods=['GET', 'POST'])
def check():
    if request.method == "GET":
        username=request.args.get('username')
        password=request.args.get('password')
        # 校验
        # 核对用户名和密码是否一致
        user = User.query.filter_by(username=username, password=password, user_status=1).first()
        # 如果用户名和密码一致
        if user:
            # 向session中写入相应的数据
            session['user_id'] = user.user_id
            session['username'] = user.username
            session['user_pic'] = user.Icon
            msg = '* 校验通过'
            return jsonify({'code': 0, 'msg': msg, 'succ': True, 'username': username})
        # 如果用户名和密码不一致返回登录页面,并给提示信息
        else:
            msg = '* 用户名或者密码不一致'
            return jsonify({'code': 0, 'msg': msg, 'succ': False})
    if request.method == "POST":
        username = request.form.get('username')
        password = request.form.get('password')
        print("username:", username)
        # 校验
        # 核对用户名和密码是否一致
        user = User.query.filter_by(username=username, password=password, user_status=1).first()
        # 如果用户名和密码一致
        if user:
            # 向session中写入相应的数据
            session['user_id'] = user.user_id
            session['username'] = user.username
            session['user_pic'] = user.Icon
            msg = '* 校验通过'
            return jsonify({'code': '00000', 'msg': msg, 'data': {'succ': True, 'username': username}})
        # 如果用户名和密码不一致返回登录页面,并给提示信息
        else:
            msg = '* 用户名或者密码不一致'
            return jsonify({'code': '00001', 'msg': msg, 'data': {'succ': False, 'username': username}})

# 用户注册
@login.route('/register', methods=['GET', 'POST'])
def register():
    print("method: ", request.method)
    print("request.content_type: ", request.content_type)
    
    if request.method == "POST":
        if request.content_type.startswith('application/x-www-form-urlencoded'):            
            # 注册新用户
            username = request.form.get('username')
            pwd1 = request.form.get('pwd1')
            pwd2 = request.form.get('pwd2')
            print(username, pwd1, pwd2)
            if not all([username, pwd1, pwd2]):
                msg, flag = '* 请填写完整信息', False
                print(msg)
                return jsonify({'code': 1, 'msg': msg, 'succ': flag})
            if len(username) > 16:
                msg, flag = '* 用户名太长', False
                print(msg)
                return jsonify({'code': 2, 'msg': msg, 'succ': flag})
            if pwd1 != pwd2:
                msg, flag = '* 两次密码不一致', False
                print(msg)
                return jsonify({'code': 3, 'msg': msg, 'succ': flag})
            u = User.query.filter(User.username == username).first()
            if u:
                msg, flag = '用户名已经存在', False
                print(msg)
                return jsonify({'code': 4, 'msg': msg, 'succ': flag})
            reg_time = time.strftime("%Y-%m-%d", time.localtime())
            user = User(username=username, password=pwd1, reg_time=reg_time)
            db.session.add(user)
            db.session.commit()
            msg, flag = '* 注册成功', True
            print(msg)
            return jsonify({'code': 0, 'msg': msg, 'succ': flag, 'username': username})
        elif request.content_type.startswith('multipart/form-data'):
            comment = request.form.get('content')
        else:
            comment = request.values.get("content")
        msg, flag = '* 请求失败', False
        print(msg)
        return jsonify({'code': 5, 'msg': msg, 'succ': flag, 'username': 'null'})

# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)

# 添加路由
@login.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        # 通过file标签获取文件
        f = request.files['file']
        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "图片类型：png、PNG、jpg、JPG、bmp"})
        # 当前文件所在路径
        basepath = os.path.dirname(__file__)
        # 一定要先创建该文件夹，不然会提示没有该路径
        upload_path = os.path.join(basepath, '../static/upload', secure_filename(f.filename))
        # 保存文件
        f.save(upload_path)
        # 返回上传成功界面
        return render_template('upload_ok.html')
    # 重新返回上传界面
    return render_template('upload.html')

@login.route('/images/<string:filename>', methods=['GET'])
def show_photo(filename):
    # 当前文件所在路径
    basepath = os.path.dirname(__file__)
    file_dir = os.path.join(basepath, '../static/upload')
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png'
            return response
    else:
        pass

@login.route('/images/goods/<string:filename>', methods=['GET'])
def goods_pic(filename):
    # 当前文件所在路径
    basepath = os.path.dirname(__file__)
    file_dir = os.path.join(basepath, '../static/goods/')
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/jpg'
            return response
    else:
        pass